import re

from lib.constant.lib_constant import LibConstant
from lib.handler.logger_handler import LoggerHandler
from lib.property.logger_property import LoggerProperty
from lib.utils.file_util import FileUtil
from lib.utils.print_util import PrintUtil


class LoggerInit(object):
    prop = None
    root_level = None

    @staticmethod
    def set_prop(prop):
        LoggerInit.prop = prop

    @staticmethod
    def start(server_name):
        PrintUtil.start("logger server start ...")
        root_path = LoggerInit.prop.get(LoggerProperty.LOG_ROOT)
        root_level = LoggerInit.prop.get(LoggerProperty.LOG_INFO_LEVEL)
        if server_name == LibConstant.SERVER_API:
            LoggerInit.init_handler("", root_path, root_level)
        else:
            _prefix = LoggerInit.prop.get(LoggerProperty.LOG_PREFIX)
            if _prefix:
                prefix_list = _prefix.split(",")
                for p in prefix_list:
                    if server_name == p:
                        LoggerInit.init_handler(p, root_path, root_level)

        LoggerHandler.root_level = str(root_level).upper()
        LoggerHandler.load_log()
        PrintUtil.start("logger server end ...")

    @staticmethod
    def init_handler(prefix, root_path, root_level):
        _prefix = ""
        p_prefix = ""
        if prefix:
            _prefix = prefix + "."
            p_prefix = prefix + "/"
        formatter = LoggerInit.prop.get(_prefix + LoggerProperty.PREFIX_LOG_FORMAT)
        date_formatter = LoggerInit.prop.get(_prefix + LoggerProperty.PREFIX_LOG_DATE_FORMAT)
        level = LoggerInit.prop.get(_prefix + LoggerProperty.PREFIX_LOG_LEVEL)
        if not level:
            level = root_level
        level_list = level.split(",")
        handler_list = []
        for l in level_list:
            path = LoggerInit.prop.get(_prefix + LoggerProperty.PREFIX_LOG_FILE + "." + l.lower())
            index = re.search(r'/[^/]+(/)', path)
            temp = ""
            if index:
                temp = path[0: index - 1]
            FileUtil.exists_folder(root_path + "/" + p_prefix + temp)
            file_path = root_path + "/" + p_prefix + path
            handler = {"l": l.upper(), "p": file_path, "f": formatter, "d": date_formatter}
            handler_list.append(handler)
            if prefix == '':
                prefix = LoggerProperty.DEFAULT
        LoggerHandler.init_list_handler(handler_list, prefix)
